package com.vvv.designpattern.pay.strategy.factory;

import com.vvv.designpattern.pay.strategy.PayStrategyInterface;
import com.vvv.designpattern.pay.strategy.context.PayContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author vvv
 * @date 2023-11-22 17 02
 * discription 工厂模式：具体工厂角色，用于创建具体的产品的
 */
@Component
public class PayContextFactory extends AbstractPayContextFactory<PayContext>  {

    public static final Map<String, PayContext> payContexts = new ConcurrentHashMap<>();

    @Override
    public PayContext getContext(Integer payType) {
        // 1. 根据payType获取对应的枚举类
        StrategyEnum strategyEnum =
                payType == 1 ? StrategyEnum.alipay :
                payType == 2 ? StrategyEnum.wechat :
                null;
        if (strategyEnum == null) {
            throw new UnsupportedOperationException("payType not supported !");
        }
        // 2. 从map中尝试获取缓存PayContext对象
        PayContext payContext = payContexts.get(strategyEnum.getValue());
        if (payContext != null) {
            return payContext;
        }
        synchronized (payContexts) {
            // double check
            payContext = payContexts.get(strategyEnum.getValue());
            if (payContext != null) {
                return payContext;
            }

            try {
                PayStrategyInterface payStrategy =
                        (PayStrategyInterface) Class.forName(strategyEnum.getValue()).newInstance();
                payContext = new PayContext(payStrategy);
                payContexts.put(strategyEnum.getValue(), payContext);
            } catch (Exception e) {
                throw new UnsupportedOperationException("Get payStrategy failed!");
            }
        }
        return payContexts.get(strategyEnum.getValue());
    }
}
